package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    //添加菜品

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("添加成功");
    }

    //分页查询菜品数据
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, String name) {
        //1.分页构造器
        Page<Dish> pg = new Page(page, pageSize);
        //2.条件构造器
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        //3.条件过滤器
        qw.like(name != null, Dish::getName, name);
        //4.排序条件
        qw.orderByDesc(Dish::getUpdateTime);
        dishService.page(pg, qw);
        long total = pg.getTotal();//总条数
        List<Dish> records = pg.getRecords();//当页显示的条目数
        Map<String, Object> map = new HashMap<>();
        map.put("total", (int) total);
        /*只有菜品分类id：categoryId，没有分类名称
        根据菜品分类id，查询菜品分类数据。在set进去
        List<Dish> records ---> List<DishDto> dishDtos*/
        List<DishDto> dishDtos = records.stream().map((dish) -> {
            //获取菜品分类id
            Long categoryId = dish.getCategoryId();
            //通过categoryId获取category对象里的属性
            Category category = categoryService.getById(categoryId);
            //通过对象获取分类的name
            String categoryName = category.getName();
            //新建一个DishDto 将分类名称set进入
            DishDto dishDto = new DishDto();
            dishDto.setCategoryName(categoryName);
            //将Dish dish 数据放入到 DishDto dishDto 里面
            BeanUtils.copyProperties(dish, dishDto);
            return dishDto;
        }).collect(Collectors.toList());
        map.put("records", dishDtos);
        return R.success(map);
    }

    //回显菜品数据
    @GetMapping("/{id}")
    public R<DishDto> get(@RequestBody Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    //修改菜品
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        Set key=redisTemplate.keys("dish_*");
        redisTemplate.delete(key);
        return R.success("修改菜品成功");
    }

    //删除菜品
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        //先删除菜品对应的口味(select * from dish_flavor where id in(1,2,3);
        LambdaQueryWrapper<DishFlavor> qw1 = new LambdaQueryWrapper<>();
        qw1.in(DishFlavor::getDishId, ids);
        dishFlavorService.remove(qw1);
        //删除菜品
        dishService.removeByIds(ids);
        return R.success("删除成功");
    }

    //启用禁用
    @PostMapping("/status/{status}")
    public R<String> updateById(@PathVariable Integer status, @RequestParam List<Long> ids) {
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(status);
            dishService.updateById(dish);
        }
        return R.success("操作成功");
    }

    //根据分类id查询该分类下的所有菜品集合
    @GetMapping("/list")
    public R<List<DishDto>> getcategoryId(Dish dish) {
        List<DishDto> dishDtoList = null;
//动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();//dish_1397844391040167938_1
//先从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dishDtoList != null){
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList);
        }
        //1.dish表中状态为1的
        LambdaQueryWrapper<Dish> qw1 = new LambdaQueryWrapper<>();
        qw1.eq(Dish::getCategoryId, dish.getCategoryId());
        qw1.eq(Dish::getStatus, 1);
        List<Dish> list = dishService.list(qw1);
        dishDtoList = list.stream().map((lg) -> {
            //2.new一个dto对象，将dish转移到dto中
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(lg, dto);
            //3.查询口味数据
            LambdaQueryWrapper<DishFlavor> qw2 = new LambdaQueryWrapper<>();
            qw2.eq(DishFlavor::getDishId, lg.getId());
            List<DishFlavor> flavors = dishFlavorService.list(qw2);
            //4.set到dto中的集合变量中
            dto.setFlavors(flavors);
            return dto;
        }).collect(Collectors.toList());
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}
